﻿namespace OPC
{
    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.Linq;
    using System.Configuration;
    public class OpcBusiness
    {
        private object D11220_Value;
        private object D11420_Value;
        private object D11421_Value;
        private object D11422_Value;
        private object D11423_Value;
        private object D11424_Value;
        private object D11425_Value;
        private object D11426_Value;
        private object D11446_Value;
        private object D11447_Value;
        private object D11448_Value;
        private object D11449_Value;
        private static readonly OPC.OpcBusiness instance = new OPC.OpcBusiness();
        public List<string> lstItemIDs = new List<string>();
        private static string ChanneDevice = ConfigurationManager.AppSettings["ChanneScanCodeDevice"].ToString(); 
        /// <summary>
        /// TW存储标记名和值
        /// </summary>
        public Dictionary<string, object> dicTagValue = new Dictionary<string, object>();
        public object[] NewValues = null;

        public void DisOpc()
        {
            OPC.OpcHandle instance = OPC.OpcHandle.GetInstance();
            if (instance.ItemIDs != null)
            {
                instance.DisOpc();
            }
        }

        public static OPC.OpcBusiness GetInstance()
        {
            return instance;
        }

        public void Init()
        {
            this.OpcConnect();
        }
        //TW重载，动态添加item
        /// <summary>
        /// TW重载，动态添加item,如Channel1.Device1.D11420
        /// </summary>
        /// <param name="lstItem"></param>
        public void Init(List<string> lstItem)
        {
            OpcConnect(lstItem);
        }
        private void OpcConnect()
        {
            bool flag;
            OPC.KanBan.初始系统所辖计算机信息();
            if (!OPC.KanBan.检查计算机信息())
            {
                return;
            }
            int x = 0;
        Label_0102:
            flag = true;
            OPC.OpcHandle instance = OPC.OpcHandle.GetInstance();
            if (instance.ItemIDs == null)
            {
                this.lstItemIDs = new List<string>();
                string argDescription = ""; 
                this.lstItemIDs.Add(ChanneDevice + "DSH1122020");
                for (int i = 0; i < 11; i++)
                {
                     int num2 = 0x2c9c + i;
                    string tempAddress  = ChanneDevice + "D" + i.ToString();
                    this.lstItemIDs.Add(  tempAddress);
                }
                instance.ConnectPLC(this.lstItemIDs.ToArray(), ref argDescription);
                if (argDescription.Contains("成功"))
                {
                    new Thread(new ThreadStart(this.ReadOpcHandle)) { IsBackground = true }.Start();
                }
                else
                {
                    if(x>3)
                    {
                        goto Label_0103;
                    }
                    x++;

                    Thread.Sleep(0x2710);
                     goto Label_0102;
                } 
            }
            Label_0103:
            Console.WriteLine("test");
        }
        /// <summary>
        /// TW重载，动态添加item,如Channel1.Device1.D11420
        /// </summary>
        /// <param name="lstItem"></param>
        private void OpcConnect(List<string> lstItem)
        {
           
            bool flag;
            OPC.KanBan.初始系统所辖计算机信息();
            if (!OPC.KanBan.检查计算机信息())
            {
                return;
            }
        Label_0102:
            flag = true;
            OPC.OpcHandle instance = OPC.OpcHandle.GetInstance();
            if (instance.ItemIDs == null)
            {
                this.lstItemIDs = new List<string>();
                string argDescription = "";
                //string str2 = "Channel1.Device1.";
                //this.lstItemIDs.Add(str2 + "DSH1122020");
                //for (int i = 0; i < 11; i++)
                //{
                //    int num2 = 0x2c9c + i;
                //    this.lstItemIDs.Add(str2 + "D" + num2.ToString().Trim());
                //}
                this.lstItemIDs = lstItem;
                instance.ConnectPLC(this.lstItemIDs.ToArray(), ref argDescription);
                if (argDescription.Contains("成功"))
                {
                    new Thread(new ThreadStart(this.ReadOpcHandle)) { IsBackground = true }.Start();
                }
                else
                {
                    Thread.Sleep(0x2710);
                    goto Label_0102;
                }
            }
        }
        public object ReadData(string sAddress)
        {
            switch (sAddress)
            {
                case "D11220":
                    return this.D11220_Value;

                case "D11420":
                    return this.D11420_Value;

                case "D11421":
                    return this.D11421_Value;

                case "D11422":
                    return this.D11422_Value;

                case "D11423":
                    return this.D11423_Value;

                case "D11424":
                    return this.D11424_Value;

                case "D11425":
                    return this.D11425_Value;

                case "D11426":
                    return this.D11426_Value;

                case "D11446":
                    return this.D11446_Value;

                case "D11447":
                    return this.D11447_Value;

                case "D11448":
                    return this.D11448_Value;

                case "D11449":
                    return this.D11449_Value;
            }
            return null;
        }
        /// <summary>
        /// 读取标记值
        /// </summary>
        /// <param name="sAddress"></param>
        /// <returns></returns>
        public object ReadDataTW(string sAddress)
        {
            object obj=null;
            obj = getDictionaryKV(dicTagValue,sAddress);
            return obj;
        }
        private void ReadOpcHandle()
        {
            while (true)
            {
                try
                {
                    int[] argsQualities = new int[1];
                    OPC.OpcHandle instance = OPC.OpcHandle.GetInstance();
                    object[] objValues = instance.ReadItems(instance.ItemIDs, ref argsQualities);
                    for (int i = 0; i < argsQualities.Length; i++)
                    {
                        if (argsQualities[i] != 0xc0)
                        {
                        }
                    }
                    this.NewValues = objValues;
                    //this.SetData(objValues);
                    SetDataTW(objValues);
                    if (Convert.ToInt32(objValues[8]) == 1)
                    {
                    }
                }
                catch
                {
                }
                Thread.Sleep(200);
            }
        }

        private void SetData(object[] objValues)
        {
            int index = -1;
            index++;
            this.D11220_Value = objValues[index];
            index++;
            this.D11420_Value = objValues[index];
            index++;
            this.D11421_Value = objValues[index];
            index++;
            this.D11422_Value = objValues[index];
            index++;
            this.D11423_Value = objValues[index];
            index++;
            this.D11424_Value = objValues[index];
            index++;
            this.D11425_Value = objValues[index];
            index++;
            this.D11426_Value = objValues[index];
            index++;
            this.D11446_Value = objValues[index];
            index++;
            this.D11447_Value = objValues[index];
            index++;
            this.D11448_Value = objValues[index];
            index++;
            this.D11449_Value = objValues[index];
        }
        /// <summary>
        /// 存储读取到的值
        /// </summary>
        /// <param name="objValues"></param>
        private void SetDataTW(object[] objValues)
        {
            int countTag = lstItemIDs.Count;
            for (int i = 0; i < countTag; i++)
            {
                setDictionaryKV(dicTagValue,lstItemIDs[i],objValues[i]);
            }
        }
        public bool WriteData(string sAddress, object argValue, ref int argError)
        {
            OPC.OpcHandle instance = OPC.OpcHandle.GetInstance();
            int num = -1;
            if (sAddress == "D11220")
            {
                //sAddress = "DSH11220.20";
                sAddress = "DSH1122020";
            }
            sAddress = "Channel1.Device1." + sAddress;
            return instance.WriteItems(sAddress, argValue, ref num);
        }
        /// <summary>
        /// 写值
        /// </summary>
        /// <param name="sAddress"></param>
        /// <param name="argValue"></param>
        /// <param name="argError"></param>
        /// <returns></returns>
        public bool WriteDataTW(string sAddress, object argValue, ref int argError)
        {
            OPC.OpcHandle instance = OPC.OpcHandle.GetInstance();
            int num = -1;
            //if (sAddress == "D11220")
            //{
            //    //sAddress = "DSH11220.20";
            //    sAddress = "DSH1122020";
            //}
            //sAddress = "Channel1.Device1." + sAddress;
            return instance.WriteItems(sAddress, argValue, ref num);
        }
        /// <summary>
        /// 获取指定字典，指定键值
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="stringKey"></param>
        /// <returns></returns>
        private static object getDictionaryKV(Dictionary<string, object> dic, string stringKey)
        {
            object stringRtn;
            if (dic.Keys.Contains(stringKey))
                stringRtn = dic[stringKey];
            else
                stringRtn = null;
            return stringRtn;
        }
        /// <summary>
        /// 设定指定字典指定键值，存在则修改，不存在则添加
        /// </summary>
        /// <param name="dic"></param>
        /// <param name="stringKey"></param>
        /// <param name="stringValue"></param>
        /// <returns></returns>
        private static void setDictionaryKV(Dictionary<string, object> dic, string stringKey, object stringValue)
        {
            if (dic.Keys.Contains(stringKey))
                dic[stringKey] = stringValue;
            else
                dic.Add(stringKey, stringValue);
        }
    }
}

